# -*- coding: UTF-8 -*-
#!/usr/local/bin/python

# whole process
# one huge text file -> small *.txt files  -> *.html files (chapters)-> epub
#
# In this html2epub.py:
# input    : one folder contains all *.html files
# output   : an epub file
#

import os
import sys
import getopt
import re
import argparse

import epubbuilder

from datetime import datetime
from lxml import etree
import traceback

class HtmlFiles:
    
    def __init__(self, src_dir, dest_dir):
        self.src_dir = src_dir
        self.dest_dir = dest_dir
    
    def _exportchapters(self, epub):
        chapters = self.root.xpath("/rss/channel/item")
        for chp in chapters:
            if self._get_text(chp.xpath("wp:status", namespaces=self.root.nsmap)) != 'publish':
                continue
            fid = -1
            try:
                fid = int(self._get_text(chp.xpath("wp:post_id", namespaces=self.root.nsmap)))
                title, post = self._format_chapter(chp)
                epub.add_chapter(fid, title, post)
            except:
                print ("Error filename: %s" % fid)
                traceback.print_exc()

    def _copyimages(self, epub):
        for root, dirs, files in os.walk(self.src_dir):
            if root == self.src_dir:
                pass
            elif os.path.basename(root) == 'images':
                for f in files:
                    epub.add_image(os.path.join(root, f))
        
    def process(self, epub):
        info = self._get_bloginfo()
        epub.set_info(**info)
        self._exportchapters(epub)
        self._copyimages(epub) 

if __name__ == '__main__':  
    
    argument_parser = argparse.ArgumentParser(description='Translate html files to an epub file')
    argument_parser.add_argument('-i', dest = 'srcDir', help='the source folder name')
    argument_parser.add_argument('-o', dest = 'destDir', help='the destination folder name')
    
    args = argument_parser.parse_args()
    
    srcDir = args.srcDir
    destDir = args.destDir
    
    epub = EpubData()
    html = HtmlFiles(srcDir)
    html.process(epub)
    epub.save()
   
